﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Security.Claims;
using gt.dotnetcore.webapi.extension.Services;

namespace gt.dotnetcore.webapi.extension.Filters
{
    public class BasicAuthorizationFilterAttribute : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var isAnonymous = (context.Filters.Any(e => (e as AllowAnonymousAttribute) != null));
            if (isAnonymous) return;

            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                context.Result = new UnauthorizedResult();
                return;
            }
            var checkService = context.HttpContext.RequestServices.GetService(typeof(IPermissionCheckService)) as IPermissionCheckService;
            if (checkService == null) return;

            var appkey = context.HttpContext.User.Identity?.Name;
            var routeCollection = context.ActionDescriptor.RouteValues;
            var controllerName = routeCollection["controller"];
            var actionName = routeCollection["action"];

            if (!checkService.Check(appkey, controllerName + "/" + actionName))
            {
                context.Result = new ForbidResult();
                return;
            }
        }
    }
}
